<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-if="optType !='view' "
          v-hasPermi="['rr:requisition:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rr:requisitionline:edit']"
        >修改</el-button>
      </el-col>-->
<!--      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rr:requisitionline:remove']"
        >删除</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requisitionlineList" @selection-change="handleSelectionChange">
      <el-table-column label="序号"  type="index" width="50"/>
      <el-table-column label="物料编码" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="库区" align="center" prop="locationName" />
      <el-table-column label="库位" align="center" prop="areaName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        v-for="col in columnsConfig"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        :align="col.align"
        v-if="col.show">
      </el-table-column>
      <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" fixed="right"/>
      <el-table-column label="退料数量（主）" align="center" prop="quantityIssued" fixed="right"/>
      <el-table-column label="单位（辅）" align="center" prop="storageUnit"  fixed="right"/>
      <el-table-column label="退料数量（辅）" align="center"   prop="storageUnitquantity" fixed="right">
        <template slot-scope="scope">
         {{ scope.row.storageUnitquantity }}
<!--          <el-tag type="success" v-if="'Y' == scope.row.enableMultiUnit">{{ scope.row.storageUnitquantity }}</el-tag>
          <span v-else></span>-->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" v-if="optType !='view' ">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rr:requisition:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['rr:requisition:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改返修退料单体对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="990px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物料编码" prop="itemCode" readonly>
              <el-input v-model="form.itemCode" readonly="readonly" placeholder="请选择产品物料编码">
                <el-button slot="append" @click="handleSelectStock" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
<!--            <StockSelect ref="stockSelect" @onSelected="onStockSelected"  ></StockSelect>-->
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected"></ItemSelect>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入物料名称" readonly/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-if="this.enableBatchFlag =='Y'">
            <el-form-item label="批次号" prop="batchCode">
              <!--            要求可以手动填写  readonly="readonly"-->
              <el-input v-model="form.batchCode"  placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="this.enableBatchFlag =='Y'">
            <el-form-item label-width="60">
              <el-switch
                v-model="autoGenCodeFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenCode(autoGenCodeFlag)"
                v-if="optType != 'view'"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位（主）" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="请输入单位" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退料数量（主）" prop="quantityIssued" label-width="100" style="width: 100%">
              <!--              <el-input v-model="form.quantityIssued" placeholder="请输入退料数量" />-->
              <el-input-number :min=0 :step="0.01" :precision="2" v-model="form.quantityIssued" @change="handleChangeZhu" placeholder="请输入退料数量"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.enableMultiUnit === 'Y'">
          <el-col :span="12">
            <el-form-item label="单位（辅）" prop="storageUnit">
              <el-input v-model="form.storageUnit" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退料数量（辅）" prop="storageUnitquantity" label-width="110px" style="width: 100%">
              <el-input-number
                :min="0"
                :step="0.01"
                :precision="2"
                v-model="form.storageUnitquantity"
                @change="handleChangeFu"
                placeholder="请输入数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.enableMultiUnit === 'Y'">
          <el-col :span="12">
            <el-form-item label="换算方式" prop="storageUnitType">
              <el-input :value="form.storageUnitType === 'fixed' ? '固定' : '浮动'"  readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="换算比例" prop="storageRatio" v-if="form.storageUnitType === 'fixed'">
              <el-input-number
                :min="0"
                v-model="form.storageRatio"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="接收仓库" prop="warehouseId">
              <el-cascader v-model="warehouseInfo"
                           :options="warehouseOptions"
                           :props="warehouseProps"
                           style="width:100%"
                           @change="handleWarehouseChanged"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReturnline, getReturnline, delReturnline, addReturnline, updateReturnline } from "@/api/mes/rr/returnline";
import {genCode} from "@/api/system/autocode/rule";
import {getTreeList} from "@/api/mes/wm/warehouse";
import ItemSelect from "@/components/itemSelect/single.vue";
import {getMdItem} from "@/api/mes/md/mdItem";
import Template from "@/views/print/printtemplate/list.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";

export default {
  name: "Returnline",
  components: {Template, ItemSelect},
  props: {
    optType: null,
    orderId: null,

  },
  data() {
    return {
      columnsConfig:[],
      enableBatchFlag:null,
      autoGenCodeFlag:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 返修退料单体表格数据
      requisitionlineList: [],
      warehouseCode: 'XBK_VIRTUAL', //线边库
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId:this.orderId,
        itemCode: null,        itemName: null,      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          {required: true, message: "物料编码不能为空", trigger: "blur"}
        ],
        quantityIssued: [
          {required: true, message: "退料数量不能为空", trigger: "blur"},
          { validator: this.checkQuantity, trigger: 'blur' }
        ],
        batchCode: [
          {required: true, message: "批号不能为空", trigger: "blur"}
        ],
        warehouseId:[
          {required: true, message: "仓库不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    console.log("createtttttt",this.requisitionlineList)
    this.getList();
    this.getWarehouseList()
    this.getItemBase()
  },
  methods: {
    checkQuantity(rule, value, callback) {
      if (value <= 0) {
        return callback(new Error('退料数量必须大于0'));
      }
      callback(); // 如果值大于0，则通过校验
    },
    /** 查询返修退料单体列表 */
    getList() {

      if(this.orderId){
        console.log("33333")
        this.loading = true;
        listReturnline(this.queryParams).then(response => {
          this.requisitionlineList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }else{
        this.loading = false
      }
      // this.$emit('change',this.requisitionlineList);
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    handleChangeZhu(value){
      if('Y' == this.form.enableMultiUnit) {
        if (this.form.storageUnitType === 'fixed') {
          // 库存单位数量=主数量 / 换算比例
          this.form.storageUnitquantity = parseFloat(
            (this.form.quantityIssued / this.form.storageRatio).toFixed(7)
          );
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (this.form.storageUnitType === 'float') {
          this.handleFloatCalculate()
        }

      }
    },
    handleChangeFu(){
      if (this.form.storageUnitType === 'fixed') {
        // 主数量 = 库存单位数量 * 换算比例
        this.form.quantityIssued = parseFloat(
          (this.form.storageUnitquantity * this.form.storageRatio).toFixed(7)
        );
      }
      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (this.form.storageUnitType === 'float') {
        this.handleFloatCalculate()
      }
    },
    handleFloatCalculate(triggerSource) {
      //浮动就根据两个数量计算出浮动率就可以了
      if (this.form.storageUnitType !== 'float') return;

      if (this.form.storageUnitquantity > 0 && this.form.quantityIssued > 0) {
        console.log("mmmmmmmmmmmm")
        // 计算新换算比例 = 主数量 / 库存单位数量
        this.form.storageRatio = parseFloat(
          (this.form.quantityIssued / this.form.storageUnitquantity).toFixed(4)
        );
      }
    },

    handleSelectStock() {
      this.$refs.itemSelect.showFlag = true;
      this.$refs.itemSelect.getList();
    },
    //物料选择弹出框
    onItemSelected(obj) {
      this.reset()
      if (obj != undefined && obj != null) {
        getMdItem(obj.itemId).then(response => {
          this.form.enableMultiUnit=response.data.enableMultiUnit
          this.form.storageUnit=response.data.storageUnit
          this.form.storageUnitType=response.data.storageUnitType
          this.form.storageRatio=response.data.storageRatio

          this.form.itemId = obj.itemId;
          this.form.itemCode = obj.itemCode;
          this.form.itemName = obj.itemName;
          this.form.specification = obj.specification;
          this.form.unitOfMeasure = obj.unitOfMeasure;
          this.enableBatchFlag = obj.enableBatchFlag;
        })

        this.$forceUpdate()
      }
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj) {
      console.log("cccccc",obj)
      console.log("ccc",this.warehouseOptions)
      if (obj != null) {
        const ck= this.findWarehouseInfo(obj[0],obj[1],obj[2])
        console.log('kkkkkkkkkkk',ck)
        this.form.warehouseId=ck.warehouse.id
        this.form.warehouseName=ck.warehouse.name
        this.form.warehouseCode=ck.warehouse.code

        this.form.locationId=ck.location.id
        this.form.locationName=ck.location.name
        this.form.locationCode=ck.location.code

        this.form.areaId=ck.area.id
        this.form.areaName=ck.area.name
        this.form.areaCode=ck.area.code

      }

    },
    findWarehouseInfo(warehouseId, locationId, areaId) {
      // 查找匹配的仓库
      const warehouse = this.warehouseOptions.find(w => w.pId === warehouseId);
      if (!warehouse) return null;
      console.log('wwwww',warehouse)
      // 在仓库内查找匹配的库区
      const location = warehouse.children?.find(l => l.pId === locationId);
      if (!location) return null;
      console.log("llll",location)
      // 在库区内查找匹配的库位
      const area = location.children?.find(a => a.pId === areaId);
      if (!area) return null;
      console.log("aaaaa",area)
      // 返回结构化结果
      return {
        warehouse: {
          id: warehouse.pId,
          name: warehouse.pName,
          code: warehouse.warehouseCode
        },
        location: {
          id: location.pId,
          name: location.pName,
          code: location.locationCode
        },
        area: {
          id: area.pId,
          name: area.pName,
          code: area.areaCode
        }
      };
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        orderId: null,        materialStockId: null,        itemId: null,        itemCode: null,        itemName: null,        specification: null,        unitOfMeasure: null,        quantityIssued: null,        batchCode: null,        warehouseId: null,        warehouseCode: null,        warehouseName: null,        locationId: null,        locationCode: null,        locationName: null,        areaId: null,        areaCode: null,        areaName: null,        remark: null,        createBy: null,        createTime: null,        createByName: null,        updateBy: null,        updateTime: null,        tenantId: null      };
      this.resetForm("form");
        this.warehouseInfo=[]
      this.enableBatchFlag=null
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加返修退料单体";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
  /* 单据头体一起修改
   console.log('hhhhhhh',row)
      // 直接使用当前行数据（不再调用API）
      this.form = {...row};  // 使用浅拷贝
      this.$nextTick(() => {
        this.warehouseInfo = [
          row.warehouseId,
          row.locationId,
          row.areaId
        ];
      });
      this.open = true;
      this.title = "修改返修退料";*/
      const id = row.id || this.ids
      getReturnline(id).then(response => {
        this.form = response.data;
        this.warehouseInfo = [
          response.data.warehouseId,
          response.data.locationId,
          response.data.areaId
        ];
        this.open = true;
        this.title = "修改返修退料单体";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.quantityIssued <= 0) {
            this.$modal.msgError("退料数量（主）必须大于0");
            return
          }

          if (this.form.enableMultiUnit == 'Y') {
            if (this.form.storageUnitquantity <= 0) {
              this.$modal.msgError("退料数量（辅）必须大于0");
              return
            }
          }
          this.form.orderId=this.orderId
          console.log("ssssssssssss",this.form)
          if (this.form.id != null) {
            updateReturnline(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log("ssssssssssss",this.form)
            addReturnline(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
/*单据头体一起
  this.$refs["form"].validate(valid => {
        if (valid) {
          // 新增：判断是新增还是修改操作
          if (this.form.id) {
            // 修改现有行
            const index = this.requisitionlineList.findIndex(tableitem => tableitem.id === this.form.id);
            if (index !== -1) {
              this.requisitionlineList.splice(index, 1, {...this.form});
            }
          } else {
            // 新增行
            // 添加orderId关联
            this.form.orderId = this.orderId;
            this.requisitionlineList.push({...this.form});
          }

          this.open = false;
          // 触发事件通知父组件
          this.$emit('change',this.requisitionlineList);

        }
      });*/
    },
    /** 删除按钮操作 */
    handleDelete(row) {
         this.$modal.confirm('是否确认删除返修退料单体编号为"' + row.itemName + '"的数据项？').then(function() {
       return delReturnline(row.id);
     }).then(() => {
       this.getList();
       this.$modal.msgSuccess("删除成功");
     }).catch(() => {});
 /*     删除在单据头 起作用
 // 删除时  已有ID的行通过ID删除 五id直接找到对象删除
      if (row.id) {
        // 已有ID的行通过ID删除
        const index = this.requisitionlineList.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.requisitionlineList.splice(index, 1);
        }
      } else {
        // 新增的删除
        const index = this.requisitionlineList.indexOf(row);
        if (index !== -1) {
          this.requisitionlineList.splice(index, 1);
        }
      }
      // 重置选中状态
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.$emit('change', this.requisitionlineList);*/

    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });

        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    //自动生成批次号
    handleAutoGenCode(autoGenCodeFlag) {
      if (autoGenCodeFlag) {
        genCode('BATCH_CODE_NEW').then(response => {
          this.form.batchCode = response;
        });
      } else {
        this.form.batchCode = null;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rr/requisitionline/export', {
        ...this.queryParams
      }, `requisitionline_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
